package com.boom.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boom.config.Constants;
import com.boom.pojo.User;
import com.boom.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@EnableAutoConfiguration
@Controller
public class LoginController {
    //实例化UserService接口
    @Resource
    private UserService userService;

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * 主页页面
     */
    @RequestMapping(value = "/main.html")
    public String main() {
        return "frame";
    }


    /**
     * 根据和id查询-登录
     * @return
     */
    @RequestMapping(value = "/dologin.html",method = RequestMethod.POST)
    public String dologin(@RequestParam String userCode, @RequestParam String  userPassword, HttpServletRequest request,HttpSession session){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("userCode",userCode);
        //调用Service 方法进行用户匹配
        User user =userService.getUser(wrapper);
        if (user!=null){
            if (user.getUserPassword().equals(userPassword)){
                session.setAttribute(Constants.USER_SESSION,user);

                return "redirect:/main.html";
            }else{
                request.setAttribute("error","登录失败，密码不正确");
                request.setAttribute("userCode",userCode);
                return "/login";
            }
        }else{
            request.setAttribute("error","登录失败，用户不存在");
            return  "/login";
        }
    }

    /**
     * 退出到登录界面
     * @return
     */
    @RequestMapping("/logout.html")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "redirect:/login";
    }
}
